package controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import pojo.Loaisanpham;
import pojo.Nhasanxuat;
import pojo.Sanpham;
import util.BeanUtil;
import util.ConvertHelper;
import util.MessageNotificationHepler;
import util.MyHelper;
import dao.LoaisanphamDAO;
import dao.NhasanxuatDAO;
import dao.SanphamDAO;

@ManagedBean(name = "themSanPhamBean")
@SessionScoped
public class ThemSanPhamBean implements Serializable {

	private List<Loaisanpham> lstLoaiSanPham;
	private List<Nhasanxuat> lstNhaSanXuat;

	private static final long serialVersionUID = 1L;
	private Sanpham sanpham = new Sanpham();

	private int maNhomSanPham = -1;
	private int maLoaiSanPham;
	private int maNhaSanXuat;

	private boolean isSuaThongTin;
	private String titleText;

	@PostConstruct
	public void init() {
		lstLoaiSanPham = ((HeaderBean) BeanUtil.findBean("headerBean"))
				.getLstLoaiSanPham();
		lstNhaSanXuat = (new NhasanxuatDAO()).GetListNhaSanXuat(false);

		setIsSuaThongTin(false);
		setTitleText("Thêm");
	}

	public String ChuyenQuaTrangThemSanPham() {
		sanpham = new Sanpham();
		return "TrangThemSanPham?faces-redirect=true";
	}

	public String ChuyenQuaTrangSuaSanPham(Sanpham sp) {
		sanpham = sp;
		setMaNhomSanPham(sanpham.getLoaisanpham().getNhomsanpham().getManhom());
		setMaLoaiSanPham(sanpham.getLoaisanpham().getMaloaisanpham());
		setMaNhaSanXuat(sanpham.getNhasanxuat().getManhasanxuat());
		setIsSuaThongTin(true);

		setTitleText("Sửa");
		return "TrangThemSanPham";
	}

	public void changeNhomListener(AjaxBehaviorEvent event) {
		System.out.println("listener: called by "
				+ event.getComponent().getClass().getName());

		HtmlSelectOneMenu combobox = (HtmlSelectOneMenu) event.getComponent();
		int contentValue = (int) combobox.getValue();

		System.out.println(combobox.getId() + " -- " + contentValue);

		setMaNhomSanPham(contentValue);
		ThayDoiGiaTriLoaiSanPham();
	}

	public void ThayDoiGiaTriLoaiSanPham() {
		System.out.println("Thay doi gia tri Loai SP: " + getMaNhomSanPham());
		if (-1 == getMaNhomSanPham())
			setLstLoaiSanPham(((HeaderBean) BeanUtil.findBean("headerBean"))
					.getLstLoaiSanPham());
		else {
			setLstLoaiSanPham((new LoaisanphamDAO())
					.GetLoaiSanPhamTheoMaNhom(getMaNhomSanPham(), false));
		}
	}

	public void ThemSanPham() {
		System.out.println("Them: " + sanpham.getTensanpham() + " - "
				+ sanpham.getGiaban() + " - " + sanpham.getXuatxu());
		SanphamDAO spdao = new SanphamDAO();

		String nowTime = ConvertHelper.GetNowTime();
		if (uploadedFile == null) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(String
							.format("Hình ảnh chưa được chọn..!!")));
			return;
		} else {
			if (!uploadImage(uploadedFile, nowTime))
				return;
		}

		sanpham.setDaxoa(false);
		sanpham.setLoaisanpham((new LoaisanphamDAO()).get(getMaLoaiSanPham()));
		sanpham.setNgaynhansanpham(Calendar.getInstance().getTime());
		sanpham.setNhasanxuat((new NhasanxuatDAO()).get(getMaNhaSanXuat()));
		sanpham.setSoluongban(0);
		sanpham.setSoluongtronggiohang(0);
		sanpham.setSoluotxem(0);
		sanpham.setHinhanh(nowTime + uploadedFile.getName());

		try {
			spdao.saveOrUpdate(sanpham);
		} catch (Exception ex) {
			MessageNotificationHepler
					.ShowMessage("Có Lỗi trong việc thực hiện thao tác!");
			return;
		}

		System.out.println("Them Complete!!");

		MessageNotificationHepler.ShowMessage(String.format(
				"Sản phẩm '%s' đã được thêm thành công!",
				sanpham.getTensanpham()));

		sanpham = new Sanpham();
	}

	public void SuaSanPham() {
		System.out.println("Sửa: " + sanpham.getTensanpham() + " - "
				+ sanpham.getGiaban() + " - " + sanpham.getXuatxu());
		SanphamDAO spdao = new SanphamDAO();

		String nowTime = ConvertHelper.GetNowTime();
		if ((uploadedFile == null)) {
			// Ta Không làm gì cả, vì Null tức là không sửa ảnh
		} else {
			if (!uploadImage(uploadedFile, nowTime))
				return;
		}

		sanpham.setDaxoa(false);
		sanpham.setLoaisanpham((new LoaisanphamDAO()).get(getMaLoaiSanPham()));
		sanpham.setNgaynhansanpham(Calendar.getInstance().getTime());
		sanpham.setNhasanxuat((new NhasanxuatDAO()).get(getMaNhaSanXuat()));
		sanpham.setSoluongban(0);
		sanpham.setSoluongtronggiohang(0);
		sanpham.setSoluotxem(0);
		if ((uploadedFile != null))
			sanpham.setHinhanh(nowTime + uploadedFile.getName());

		// Cần kiểm tra lại điều kiện hình ảnh
		try {
			spdao.saveOrUpdate(sanpham);
		} catch (Exception ex) {
			MessageNotificationHepler
					.ShowMessage("Có Lỗi trong việc thực hiện thao tác!");

			return;
		}

		System.out.println("Sửa Complete!!");
		MessageNotificationHepler.ShowMessage(String.format(
				"Sản phẩm '%s' đã được cập nhật thành công!",
				sanpham.getTensanpham()));

		sanpham = new Sanpham();
	}

	// ---------------------
	private UploadedFile uploadedFile;

	public boolean uploadImage(UploadedFile upFile, String nowTime) {

		boolean result = MyHelper.UploadFile(upFile, nowTime,
				"/Images/Products/");

		String fileName = FilenameUtils.getName(upFile.getName());
		String contentType = upFile.getContentType();
		// --------------------

		FacesContext
				.getCurrentInstance()
				.addMessage(
						null,
						new FacesMessage(
								String.format(
										"File '%s' với định dạng '%s' đã được upload thành công!",
										nowTime + fileName, contentType)));

		return result;
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	// ------------------
	public Sanpham getSanpham() {
		return sanpham;
	}

	public void setSanpham(Sanpham sanpham) {
		this.sanpham = sanpham;
	}

	public int getMaNhomSanPham() {
		return maNhomSanPham;
	}

	public void setMaNhomSanPham(int maNhomSanPham) {
		this.maNhomSanPham = maNhomSanPham;
	}

	public int getMaLoaiSanPham() {
		return maLoaiSanPham;
	}

	public void setMaLoaiSanPham(int maLoaiSanPham) {
		this.maLoaiSanPham = maLoaiSanPham;
	}

	public int getMaNhaSanXuat() {
		return maNhaSanXuat;
	}

	public void setMaNhaSanXuat(int maNhaSanXuat) {
		this.maNhaSanXuat = maNhaSanXuat;
	}

	public List<Loaisanpham> getLstLoaiSanPham() {
		return lstLoaiSanPham;
	}

	public void setLstLoaiSanPham(List<Loaisanpham> lstLoaiSanPham) {
		this.lstLoaiSanPham = lstLoaiSanPham;
	}

	public List<Nhasanxuat> getLstNhaSanXuat() {
		return lstNhaSanXuat;
	}

	public void setLstNhaSanXuat(List<Nhasanxuat> lstNhaSanXuat) {
		this.lstNhaSanXuat = lstNhaSanXuat;
	}

	public String getTitleText() {
		return titleText;
	}

	public void setTitleText(String titleText) {
		this.titleText = titleText;
	}

	public boolean getIsSuaThongTin() {
		return isSuaThongTin;
	}

	public void setIsSuaThongTin(boolean isSuaThongTin) {
		this.isSuaThongTin = isSuaThongTin;
	}

}
